package org.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmployeeInformationDAO {
    private static final String URL = "jdbc:mysql://localhost:3306/employee";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    // 添加员工信息
    public void addEmployeeInformation(EmployeeInformation employee) {
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement("INSERT INTO employee_information (identity_card_number, gender, mobile_phone, email, employee_name, employee_number, business_trip_id, department_number) VALUES (?,?,?,?,?,?,?,?)")) {
            statement.setString(1, employee.getIdentityCardNumber());
            statement.setString(2, employee.getGender());
            statement.setString(3, employee.getMobilePhone());
            statement.setString(4, employee.getEmail());
            statement.setString(5, employee.getEmployeeName());
            statement.setString(6, employee.getEmployeeNumber());
            statement.setString(7, employee.getBusinessTripId());
            statement.setString(8, employee.getDepartmentNumber());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 查询所有员工信息
    public List<EmployeeInformation> getAllEmployeeInformations() {
        List<EmployeeInformation> employees = new ArrayList<>();
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement("SELECT * FROM employee_information")) {
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                EmployeeInformation employee = new EmployeeInformation();
                employee.setIdentityCardNumber(resultSet.getString("identity_card_number"));
                employee.setGender(resultSet.getString("gender"));
                employee.setMobilePhone(resultSet.getString("mobile_phone"));
                employee.setEmail(resultSet.getString("email"));
                employee.setEmployeeName(resultSet.getString("employee_name"));
                employee.setEmployeeNumber(resultSet.getString("employee_number"));
                employee.setBusinessTripId(resultSet.getString("business_trip_id"));
                employee.setDepartmentNumber(resultSet.getString("department_number"));
                employees.add(employee);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return employees;
    }
}